const { log } = require("debug/src/browser");
var express = require("express");
var router = express.Router();

// 引入封装的 mysql模块
const mysql = require("../util/mysql/mysql");

//项目广场
router.post("/projectCenter", function (req, res, next) {
  var s_id = req.body.s_id;
  const p1 = new Promise((res1, rej2) => {
    mysql.data(
      "SELECT id,p_title,p_synopsis,t_name FROM project a INNER JOIN project_mainmas b INNER JOIN teacher_mes c ON b.p_id=a.id AND a.p_teacher_id=c.t_id WHERE p_type = 0 LIMIT 12",
      [],
      function (err, rows, fields) {
        if (err) return;
        res1(rows);
      }
    );
  });
  const p2 = new Promise((res2, rej2) => {
    mysql.data(
      "SELECT c_project FROM my_collect where c_student=?",
      [s_id],
      function (err, rows, fields) {
        if (err) return;
        const newArr = rows.filter((item) => item.c_project !== null);
        res2(newArr);
      }
    );
  });
  const p3 = new Promise((res1, rej2) => {
    mysql.data(
      "SELECT * FROM project a INNER JOIN project_mainmas b INNER JOIN teacher_mes c ON b.p_id=a.id AND a.p_teacher_id=c.t_id WHERE p_type = 0",
      [],
      function (err, rows, fields) {
        if (err) return;
        res1(rows.length);
      }
    );
  });
  Promise.all([p1, p2, p3]).then((resall) => {
    res.send(
      JSON.stringify({
        code: 1,
        project: resall[0],
        collect: resall[1],
        dataLength: resall[2],
      })
    );
  });
});
//分页获取数据
router.post("/projectCenterYe", function (req, res, next) {
  var [s_id, val, keyWord] = [req.body.s_id, req.body.val, req.body.keyWord];
  const p1 = new Promise((res1, rej2) => {
    mysql.data(
      'SELECT id,p_title,p_synopsis,t_name FROM project a INNER JOIN project_mainmas b INNER JOIN teacher_mes c ON b.p_id=a.id AND a.p_teacher_id=c.t_id AND p_title LIKE "%' +
        keyWord +
        '%" LIMIT ?,12',
      [(val - 1) * 12],
      function (err, rows, fields) {
        if (err) return;
        res1(rows);
      }
    );
  });
  const p2 = new Promise((res2, rej2) => {
    mysql.data(
      "SELECT c_project FROM my_collect where c_student=?",
      [s_id],
      function (err, rows, fields) {
        if (err) return;
        const newArr = rows.filter((item) => item.c_project !== null);
        res2(newArr);
      }
    );
  });
  Promise.all([p1, p2]).then((resall) => {
    res.send(
      JSON.stringify({ code: 1, project: resall[0], collect: resall[1] })
    );
  });
});
//关键字查找
router.post("/projectCenterSecKeyword", function (req, res, next) {
  var [s_id, keyWord] = [req.body.s_id, req.body.keyWord];
  const p1 = new Promise((res1, rej2) => {
    mysql.data(
      'SELECT id,p_title,p_synopsis,t_name FROM project a INNER JOIN project_mainmas b INNER JOIN teacher_mes c ON b.p_id=a.id AND a.p_teacher_id=c.t_id AND p_title LIKE "%' +
        keyWord +
        '%" LIMIT 12',
      [],
      function (err, rows, fields) {
        if (err) return;
        res1(rows);
      }
    );
  });
  const p2 = new Promise((res2, rej2) => {
    mysql.data(
      "SELECT c_project FROM my_collect where c_student=?",
      [s_id],
      function (err, rows, fields) {
        if (err) return;
        const newArr = rows.filter((item) => item.c_project !== null);
        res2(newArr);
      }
    );
  });
  const p3 = new Promise((res1, rej2) => {
    mysql.data(
      'SELECT id,p_title,p_synopsis,t_name FROM project a INNER JOIN project_mainmas b INNER JOIN teacher_mes c ON b.p_id=a.id AND a.p_teacher_id=c.t_id AND p_title LIKE "%' +
        keyWord +
        '%"',
      [],
      function (err, rows, fields) {
        if (err) return;
        res1(rows.length);
      }
    );
  });
  Promise.all([p1, p2, p3]).then((resall) => {
    res.send(
      JSON.stringify({
        code: 1,
        project: resall[0],
        collect: resall[1],
        dataLength: resall[2],
      })
    );
  });
});
//收藏项目
router.post("/collectProject", function (req, res, next) {
  let [s_id, c_project, collect] = [
    req.body.s_id,
    req.body.c_project,
    req.body.collect,
  ];
  if (collect == 0) {
    mysql.data(
      "DELETE FROM my_collect WHERE c_project=? AND c_student=?",
      [c_project, s_id],
      function (err, rows, fields) {
        if (err) return;
        res.send(JSON.stringify({ code: 1 }));
      }
    );
  } else {
    mysql.data(
      "INSERT INTO my_collect (c_project,c_student) VALUES(?,?)",
      [c_project, s_id],
      function (err, rows, fields) {
        if (err) return;
        res.send(JSON.stringify({ code: 1 }));
      }
    );
  }
});
//项目详情信息
router.post("/projectData", function (req, res, next) {
  let id = req.body.p_id;
  const p1 = new Promise((res1, rej2) => {
    mysql.data(
      "SELECT id,p_title,t_name,p_dif,p_peopleNum,p_time,p_synopsis,p_require FROM project a INNER JOIN project_mainmas b INNER JOIN teacher_mes c ON b.p_id=a.id AND a.p_teacher_id=c.t_id WHERE ?",
      [id],
      function (err, rows, fields) {
        if (err) return;
        res1(rows[0]);
      }
    );
  });
  const p2 = new Promise((res2, rej2) => {
    mysql.data(
      "SELECT * FROM leave_words WHERE w_type=1 AND w_to=?",
      [id],
      function (err, rows, fields) {
        if (err) return;
        res2(rows.reverse());
      }
    );
  });
  Promise.all([p1, p2]).then((resall) => {
    res.send(
      JSON.stringify({
        code: 1,
        projectData: resall[0],
        projectLeaveWord: resall[1],
      })
    );
  });
});
//写留言
router.post("/writeLeaveWord", function (req, res, next) {
  let intoData = [
    req.body.u_id,
    req.body.w_main,
    req.body.w_time,
    req.body.w_type,
    req.body.w_to,
    req.body.to_type
  ];
  mysql.data(
    "SELECT s_name FROM student_mes where s_id=?",
    [req.body.u_id],
    function (err, rows1, fields) {
      if (err) return;
      intoData.push(rows1[0].s_name);
      mysql.data(
        "INSERT INTO leave_words (u_id,w_main,w_time,w_type,w_to,to_type,w_name,u_type) VALUES (?,?,?,?,?,?,?,1)",
        intoData,
        function (err, rows2, fields) {
          if (err) return;
          res.send(JSON.stringify({ code: 1 }));
        }
      );
    }
  );
});
//我的收藏
router.post("/myCollect", function (req, res, next) {
  var s_id = req.body.s_id;
  mysql.data(
    "SELECT c_project FROM my_collect where c_student=?",
    [s_id],
    function (err, rows, fields) {
      if (err) return;
      const newArr = rows.filter((item) => item.c_project !== null);
      let collectStr = "";
      newArr.forEach((e) => {
        collectStr = collectStr + "," + e.c_project;
      });
      const collectArr = collectStr.substring(1);
      mysql.data(
        "SELECT id,p_title,p_synopsis,t_name FROM project a INNER JOIN project_mainmas b INNER JOIN teacher_mes c ON b.p_id=a.id AND a.p_teacher_id=c.t_id WHERE id IN (" +
          collectArr +
          ")",
        [],
        function (err, rows, fields) {
          if (err) return;
          rows.forEach((e) => {
            e.collect = 1;
          });
          res.send(
            JSON.stringify({
              code: 1,
              project: rows,
            })
          );
        }
      );
    }
  );
});
//组队中心
router.post("/teamList", function (req, res, next) {
  mysql.data(
    "SELECT team_id,id,p_title,s_name,t_name,p_time,p_dif,p_peopleNum,t_peopleNum,s_id FROM team a INNER JOIN project b INNER JOIN student_mes c INNER JOIN project_mainmas d INNER JOIN teacher_mes e ON a.t_project=b.id AND a.t_captain=c.s_id AND b.id=d.p_id AND b.p_teacher_id=e.t_id WHERE a.t_issue=1",
    [],
    function (err, rows, fields) {
      if (err) return;
      res.send(
        JSON.stringify({
          code: 1,
          teamList: rows,
        })
      );
    }
  );
});
//申请入队
router.post("/joinTeam", function (req, res, next) {
  const [s_id, team_id] = [req.body.s_id, req.body.team_id];
  mysql.data(
    "SELECT * FROM team_member WHERE student_id=?",
    [s_id],
    function (err, rows1, fields) {
      if (err) return;
      if (rows1.length == 0) {
        mysql.data(
          "SELECT * FROM team_join WHERE tj_id=?",
          [s_id],
          function (err, tjrow, fields) {
            if (err) return;
            if (tjrow.length == 0) {
              var time = new Date().toLocaleString();
              mysql.data(
                "INSERT INTO team_join (tj_id,consent,tj_time,tj_team) VALUES (?,0,?,?)",
                [s_id, time, team_id],
                function (err, row2s, fields) {
                  if (err) return;
                  res.send(JSON.stringify({ code: 1 }));
                }
              );
            } else {
              res.send(JSON.stringify({ code: 4 }));
            }
          }
        );
      } else {
        mysql.data(
          "SELECT * FROM team_member WHERE team_Id=? AND student_id=?",
          [team_id, s_id],
          function (err, row2s, fields) {
            if (err) return;
            if (row2s.length == 0) {
              res.send(JSON.stringify({ code: 2 }));
            } else {
              res.send(JSON.stringify({ code: 3 }));
            }
          }
        );
      }
    }
  );
});
//队伍详情
router.post("/getTemeParticulars", function (req, res, next) {
  const [id, team_id] = [req.body.p_id, req.body.team_id];
  const p1 = new Promise((res1, rej2) => {
    mysql.data(
      "SELECT id,p_title,t_name,p_dif,p_peopleNum,p_time,p_synopsis,p_require FROM project a INNER JOIN project_mainmas b INNER JOIN teacher_mes c ON b.p_id=a.id AND a.p_teacher_id=c.t_id WHERE id=?",
      [id],
      function (err, rows, fields) {
        if (err) return;
        res1(rows[0]);
      }
    );
  });
  const p2 = new Promise((res2, rej2) => {
    const team = {};
    mysql.data(
      "SELECT s_id,s_name,cap FROM team_member a INNER JOIN student_mes b ON a.student_id = b.s_id WHERE team_Id=?",
      [team_id],
      function (err, rows, fields) {
        if (err) return;
        rows.forEach((e, v) => {
          if (e.cap == 1) {
            team.cap = rows[v].s_name;
            team.cap_id = rows[v].s_id;
          }
        });
        const newRows = rows.filter((item) => item.cap !== 1);
        team.t_member = newRows;
        mysql.data(
          "SELECT notice FROM team WHERE team_id=?",
          [team_id],
          function (err, rows, fields) {
            if (err) return;
            team.notice = rows[0].notice;
            res2(team);
          }
        );
      }
    );
  });
  Promise.all([p1, p2]).then((resall) => {
    res.send(
      JSON.stringify({
        code: 1,
        project: resall[0],
        team: resall[1],
      })
    );
  });
});
//我的信息
router.post("/studentMes", function (req, res, next) {
  const s_id = req.body.s_id;
  //个人信息
  const p1 = new Promise((res1, rej2) => {
    mysql.data(
      "SELECT * FROM student_mes WHERE s_id=?",
      [s_id],
      function (err, rows, fields) {
        if (err) return;
        res1(rows[0]);
      }
    );
  });
  // 获奖情况
  const p2 = new Promise((res2, rej2) => {
    mysql.data(
      "SELECT * FROM awards WHERE a_type=1 AND a_user_id=?",
      [s_id],
      function (err, rows, fields) {
        res2(rows);
      }
    );
  });
  // 我的项目
  const p3 = new Promise((res3, rej3) => {
    mysql.data(
      "SELECT team_Id  FROM team_member WHERE student_id=?",
      [s_id],
      function (err, rows1, fields) {
        if (rows1.length == 0) {
          res3([]);
        } else {
          var teamId = "";
          rows1.forEach((e) => {
            teamId = teamId + "," + e.team_Id;
          });
          teamId = teamId.substring(1);
          mysql.data(
            "SELECT id,p_title,p_synopsis,p_type FROM project a INNER JOIN project_mainmas b INNER JOIN team c ON a.id=b.p_id AND c.t_project=a.id  WHERE team_id IN (" +
              teamId +
              ")",
            [],
            function (err, rows2, fields) {
              res3(rows2);
            }
          );
        }
      }
    );
  });
  // 我的队伍
  const p4 = new Promise((res4, rej4) => {
    mysql.data(
      "SELECT myTeam_id FROM student_mes WHERE s_id=?",
      [s_id],
      function (err, rows1, fields) {
        if (err) return;
        const team = {};
        if (rows1[0].myTeam_id == null) {
          console.log(1);
          res4(team);
        } else {
          const team_id = rows1[0].myTeam_id;
          mysql.data(
            "SELECT s_id,s_name,cap FROM team_member a INNER JOIN student_mes b ON a.student_id = b.s_id WHERE team_Id=?",
            [team_id],
            function (err, rows2, fields) {
              if (err) return;
              rows2.forEach((e, v) => {
                if (e.cap == 1) {
                  team.cap = rows2[v].s_name;
                  team.cap_id = rows2[v].s_id;
                }
              });
              const newRows = rows2.filter((item) => item.cap !== 1);
              team.t_member = newRows;
              res4(team);
            }
          );
        }
      }
    );
  });
  Promise.all([p1, p2, p3, p4]).then((resall) => {
    res.send(
      JSON.stringify({
        code: 1,
        studentMes: {
          mes: resall[0],
          awards: resall[1],
          project: resall[2],
          team: resall[3],
        },
      })
    );
  });
});
//我的导师
router.post("/teacherMes", function (req, res, next) {
  const s_id = req.body.s_id;
  let t_id = 0;
  // 获取老师id
  mysql.data(
    "SELECT myTeacher_id FROM student_mes WHERE s_id=?",
    [s_id],
    function (err, rows, fields) {
      if (err) return;
      t_id = rows[0].myTeacher_id;
      // 老师信息
      const p1 = new Promise((res1, rej2) => {
        mysql.data(
          "SELECT * FROM teacher_mes WHERE t_id=?",
          [t_id],
          function (err, rows, fields) {
            if (err) return;
            res1(rows[0]);
          }
        );
      });
      // 老师奖项
      const p2 = new Promise((res2, rej2) => {
        mysql.data(
          "SELECT * FROM awards WHERE a_type=2 AND a_user_id=?",
          [t_id],
          function (err, rows, fields) {
            res2(rows);
          }
        );
      });
      // 老师负责项目
      const p3 = new Promise((res3, rej3) => {
        mysql.data(
          "SELECT id,p_title,p_synopsis FROM project a INNER JOIN project_mainmas b ON a.id=b.p_id WHERE p_teacher_id=?",
          [t_id],
          function (err, rows, fields) {
            res3(rows);
          }
        );
      });
      Promise.all([p1, p2, p3]).then((resall) => {
        res.send(
          JSON.stringify({
            code: 1,
            teacherMes: {
              mes: resall[0],
              awards: resall[1],
              project: resall[2],
            },
          })
        );
      });
    }
  );
});
//我的团队
router.post("/myTeam", function (req, res, next) {
  const s_id = req.body.s_id;
  mysql.data(
    "SELECT * FROM team_member a INNER JOIN team b ON a.team_Id=b.team_id WHERE student_id=? AND end=0",
    [s_id],
    function (err, rowss, fields) {
      if (err) return;
      if (rowss.length == 0) {
        res.send(
          JSON.stringify({
            code: 2,
          })
        );
        return;
      }
      const [id, team_id] = [rowss[0].t_project, rowss[0].team_id];
      const p1 = new Promise((res1, rej2) => {
        mysql.data(
          "SELECT id,p_title,t_name,p_dif,p_peopleNum,p_time,p_synopsis,p_require FROM project a INNER JOIN project_mainmas b INNER JOIN teacher_mes c ON b.p_id=a.id AND a.p_teacher_id=c.t_id WHERE id=?",
          [id],
          function (err, rows, fields) {
            if (err) return;
            res1(rows[0]);
          }
        );
      });
      const p2 = new Promise((res2, rej2) => {
        const team = {};
        mysql.data(
          "SELECT s_id,s_name,cap FROM team_member a INNER JOIN student_mes b ON a.student_id = b.s_id WHERE team_Id=?",
          [team_id],
          function (err, rows, fields) {
            if (err) return;
            rows.forEach((e, v) => {
              if (e.cap == 1) {
                team.cap = rows[v].s_name;
                team.cap_id = rows[v].s_id;
              }
            });
            const newRows = rows.filter((item) => item.cap !== 1);
            team.t_member = newRows;
            mysql.data(
              "SELECT * FROM team WHERE team_id=?",
              [team_id],
              function (err, rows, fields) {
                if (err) return;
                team.team_id = rows[0].team_id;
                team.notice = rows[0].notice;
                team.issue = rows[0].t_issue;
                res2(team);
              }
            );
          }
        );
      });
      const p3 = new Promise((res3, rej4) => {
        mysql.data(
          "SELECT team_join_id,s_id,s_name FROM team_join a INNER JOIN student_mes b ON a.tj_id=s_id WHERE tj_team=?",
          [team_id],
          function (err, rows, fields) {
            if (err) return;
            res3(rows);
          }
        );
      });
      Promise.all([p1, p2, p3]).then((resall) => {
        res.send(
          JSON.stringify({
            code: 1,
            project: resall[0],
            team: resall[1],
            join: resall[2],
          })
        );
      });
    }
  );
});
// 入队申请处理
router.post("/teamJoinDispose", function (req, res, next) {
  const [index, team_id, student_id, team_join_id] = [
    req.body.index,
    req.body.team_id,
    req.body.student_id,
    req.body.team_join_id,
  ];
  if (index == 1) {
    mysql.data(
      "INSERT INTO team_member (team_Id,student_id,cap) VALUES (?,?,0)",
      [team_id, student_id],
      function (err, rows, fields) {
        if (err) return;
        mysql.data(
          "DELETE FROM team_join WHERE team_join_id=?",
          [team_join_id],
          function (err, rows, fields) {
            if (err) return;
            mysql.data(
              "UPDATE student_mes SET myTeam_id=? WHERE s_id=?",
              [team_id,student_id],
              function (err, rows, fields) {
                if (err) return;
                res.send(
                  JSON.stringify({
                    code: 1,
                  })
                );
              }
            );
          }
        );
      }
    );
  } else {
    mysql.data(
      "DELETE FROM team_join WHERE team_join_id=?",
      [team_join_id],
      function (err, rows, fields) {
        if (err) return;
        res.send(
          JSON.stringify({
            code: 1,
          })
        );
      }
    );
  }
});
// 发布队伍消息
router.post("/teamMes", function (req, res, next) {
  const [team_id, student_id, team_mes, time] = [
    req.body.team_id,
    req.body.student_id,
    req.body.team_mes,
    req.body.time,
  ];
  mysql.data(
    "SELECT s_name FROM student_mes WHERE s_id=?",
    [student_id],
    function (err, rows1, fields) {
      if (err) return;
      const s_name = rows1[0].s_name;
      mysql.data(
        "INSERT INTO team_mes (tl_name,tl_time,tl_main,tl_team) VALUES (?,?,?,?)",
        [s_name, time, team_mes, team_id],
        function (err, rows, fields) {
          if (err) return;
          mysql.data(
            "UPDATE team SET notice=? WHERE team_id=?",
            [team_mes, team_id],
            function (err, rows, fields) {
              if (err) return;
              res.send(
                JSON.stringify({
                  code: 1,
                })
              );
            }
          );
        }
      );
    }
  );
});
//发布队伍
router.post("/teamIssue", function (req, res, next) {
  const [team_id, t_issue] = [req.body.team_id, req.body.t_issue];
  mysql.data(
    "UPDATE team SET t_issue=? WHERE team_id=?",
    [t_issue, team_id],
    function (err, rowss, fields) {
      if (err) return;
      res.send(JSON.stringify({ code: 1 }));
    }
  );
});
//修改信息
router.post("/changeInf", function (req, res, next) {
  const [s_id, s_phone, s_eMail] = [
    req.body.s_id,
    req.body.s_phone,
    req.body.s_eMail,
  ];
  mysql.data(
    "UPDATE student_mes SET s_phone=?,s_eMail=? WHERE s_id=?",
    [s_phone, s_eMail, s_id],
    function (err, rows, fields) {
      if (err) return;
      res.send(JSON.stringify({ code: 1 }));
    }
  );
});
module.exports = router;
